/*
 * @Author: Crism
 * @Date: 2018-10-31 09:58:30
 * @LastEditors: Crism
 * @LastEditTime: 2018-11-22 17:48:53
 * @Email: crism@qq.com
 * @Description: 
 */

const db_cms = require('../config').db_cms;
const db_user = require('../config').db_user;
const uuid = require('node-uuid');

const CommomUtil = require('../utils/CommomUtil');
/** 创建音乐专辑 或 歌单*/
module.exports.create_albums_info = create_albums_info;
async function create_albums_info(cover_id, albums_name, albums_desc, owner_id, albums_tags, albums_type) {
    let albums_id = "alb_" + uuid.v1().replace(/\-/g, '').substring(0, 28);
    let albums_id1 = db_cms.escape(albums_id);
    albums_name = db_cms.escape(albums_name);
    albums_desc = db_cms.escape(albums_desc);
    owner_id = db_cms.escape(owner_id);
    albums_tags = db_cms.escape(albums_tags);
    let sql = 'select user_name from ty_user where ty_id=' + owner_id;
    let owner_name = await db_user.queryOne(sql);
    if (owner_name != null) {
        sql = 'insert into albums_info(albums_id,cover_id,albums_name,albums_desc,owner_id,owner_name,albums_status,albums_tags,albums_type,create_time) value(' + albums_id1 + ',' + cover_id + ',' + albums_name + ',' + albums_desc + ',' + owner_id + ',"' + owner_name['user_name'] + '",0,' + albums_tags + ',' + albums_type + ',UNIX_TIMESTAMP(NOW()))';
        let flag = await db_cms.queryNum(sql);
        return flag > 0 ? albums_id : null;
    }
    return null;
}

/** 创建音乐歌单 */
// module.exports.create_playlist = create_playlist;
// async function create_playlist(albums_name, owner_id) {
//     let albums_id = "alb_" + uuid.v1().replace(/\-/g, '').substring(0, 28);
//     let albums_id1 = db_cms.escape(albums_id);
//     albums_name = db_cms.escape(albums_name);
//     owner_id = db_cms.escape(owner_id);
//     let sql = 'select user_name from ty_user where ty_id=' + owner_id;
//     let owner_name = await db_user.queryOne(sql);
//     if (owner_name != null) {
//         sql = 'insert into albums_info(albums_id,albums_name,owner_id,owner_name,albums_status,albums_type,create_time) value(' + albums_id1 + ',' + albums_name + ',' + owner_id + ',"' + owner_name['user_name'] + '",0,1,UNIX_TIMESTAMP(NOW()))';
//         let flag = await db_cms.queryNum(sql);
//         return flag > 0 ? albums_id : null;
//     }
//     return null;
// }

/** 删除音乐歌单 */
module.exports.del_playlist = del_playlist;
async function del_playlist(albums_id, owner_id) {
    albums_id = db_cms.escape(albums_id);
    owner_id = db_cms.escape(owner_id);
    let sql = 'UPDATE `albums_info` SET albums_status=1 WHERE albums_id=' + albums_id + ' AND albums_type=1 AND owner_id=' + owner_id;
    let flag = await db_cms.queryNum(sql);
    return flag < 0 ? [false, '删除失败!'] : [true, '删除成功!'];
}


/** 查询我创建的音乐专辑或歌单 列表 */
module.exports.query_my_albums_list = query_my_albums_list;
async function query_my_albums_list(begin, plen, owner_id, albums_type) {
    owner_id = db_cms.escape(owner_id);
    let sql = 'SELECT count(albums_id) total FROM `albums_info` where owner_id=' + owner_id + ' and albums_status=0 and albums_type=' + albums_type;
    let total = await db_cms.queryOne(sql);
    if (total != null && total['total'] == 0) {
        return [0, []];
    }
    sql = 'SELECT albums_id,cover_id,albums_name,albums_tags,music_num,follow_num,play_num,create_time FROM `albums_info` where owner_id=' + owner_id + ' and albums_status=0 and albums_type=' + albums_type + ' limit ' + begin + ',' + plen;
    let albums_list = await db_cms.query(sql);
    if (albums_list instanceof Array && albums_list.length > 0) {
        return [total['total'], albums_list];
    }
    return [0, []];
}

/** 查询专辑 -音乐列表 */
module.exports.query_albums_play_list = query_albums_play_list;
async function query_albums_play_list(albums_id, type, begin, plen) {
    albums_id = db_cms.escape(albums_id);
    let sql;
    type == 1 ?
        sql = 'SELECT a.music_id,a.music_audio_id,a.music_title,a.singer,a.music_status,a.comment_num,b.albums_name FROM `music_info` a,albums_info b where a.albums_id=' + albums_id + ' and a.albums_id=b.albums_id and b.albums_status=0 ORDER BY a.create_time limit ' + begin + ',' + plen :
        sql = 'SELECT music_id,audio_id,music_title,singer,music_status FROM `music_albums` where albums_id=' + albums_id + ' ORDER BY create_time limit ' + begin + ',' + plen;
    let albums_list = await db_cms.query(sql);
    if (albums_list instanceof Array && albums_list.length > 0) {
        return albums_list;
    }
    return [];
}

/** 点赞/取消点赞 */
module.exports.get_albums_like_num = get_albums_like_num;
async function get_albums_like_num(albums_id) {
    albums_id = db_cms.escape(albums_id);
    let sql = 'select like_num from albums_info WHERE albums_id=' + albums_id;
    let flag = await db_cms.queryOne(sql);
    if (flag != null) {
        return flag['like_num'];
    }
    return null;
}

/** 更新 专辑/歌单 点赞数 */
module.exports.update_albums_like_num = update_albums_like_num;
async function update_albums_like_num(albums_id, num_flag) {
    albums_id = db_cms.escape(albums_id);
    let sql = 'UPDATE albums_info SET like_num=like_num +' + num_flag + ' WHERE albums_id=' + albums_id;
    let flag = await db_cms.queryNum(sql);
    return flag < 1 ? false : true;
}

/** 更新 专辑/歌单 信息 */
module.exports.update_my_albums_info = update_my_albums_info;
async function update_my_albums_info(albums_id, albums_name, albums_desc, albums_tags, cover_id, owner_id) {
    owner_id = db_cms.escape(owner_id);
    albums_id = db_cms.escape(albums_id);
    albums_name = db_cms.escape(albums_name);
    albums_desc = db_cms.escape(albums_desc);
    albums_tags = db_cms.escape(albums_tags);
    let sql = 'UPDATE albums_info SET albums_name=' + albums_name + ', albums_desc=' + albums_desc + ', albums_tags=' + albums_tags + ', cover_id=' + cover_id + ' WHERE albums_id=' + albums_id + ' and owner_id=' + owner_id;
    let flag = await db_cms.queryNum(sql);
    return flag < 1 ? false : true;
}


/** 添加音乐到歌单 */
module.exports.add_music_to_playlist = add_music_to_playlist;
async function add_music_to_playlist(playlist_id, music_id, owner_id) {

    playlist_id = db_cms.escape(playlist_id);
    music_id = db_cms.escape(music_id);
    owner_id = db_cms.escape(owner_id);
    /** 查询歌单里是否有该记录 */
    let sql = 'select 1 FROM `music_albums` where albums_id=' + playlist_id + ' and music_id=' + music_id;
    let exist_row = await db_cms.queryOne(sql);
    if (exist_row != null && exist_row['1'] == 1) {
        return [false, '您的歌单列表中已经存在该音乐!'];
    }
    /** 查询专辑是否存在 是否属于该用户 */
    sql = 'select albums_id from albums_info where albums_id=' + playlist_id + ' and albums_type=1 and albums_status=0 and owner_id=' + owner_id;
    let albums_flag = await db_cms.queryOne(sql);
    if (albums_flag == null) {
        return [false, '歌单操作错误!'];
    }
    /** 查询音乐是否存在 */
    sql = 'SELECT music_audio_id,music_title,singer,music_status FROM music_info WHERE music_id =' + music_id;
    let music_info = await db_cms.queryOne(sql);
    if (music_info == null) {
        return [false, '音乐不存在!'];
    }
    let music_status = music_info['music_status'];
    let music_audio_id = db_cms.escape(music_info['music_audio_id']);
    let music_title = db_cms.escape(music_info['music_title']);
    let singer = db_cms.escape(music_info['singer']);

    let connection = await db_cms.getConnection();
    if (connection == null) {
        console.trace('trace connection fail');
        return [false, '服务连接异常!'];
    }
    let flag = true;
    try {
        await connection.beginTransaction();

        /** 更新音乐收藏数量 favor_num */
        sql = 'UPDATE `music_info` SET favor_num=favor_num+1 where music_id=' + music_id;
        await connection.query(sql);

        /** 更新音乐数量 music_num */
        sql = 'UPDATE albums_info SET music_num=music_num+1 WHERE albums_id=' + playlist_id;
        await connection.query(sql);

        /** 音乐歌单添加关联 */
        sql = 'INSERT INTO music_albums(music_id,albums_id,audio_id,music_title,singer,music_status,create_time) VALUE(' + music_id + ',' + playlist_id + ',' + music_audio_id + ',' + music_title + ',' + singer + ',' + music_status + ',UNIX_TIMESTAMP(NOW()))';
        await connection.query(sql);

        await connection.commit();
    } catch (err) {
        /**
         * TODO 日志系统
         */
        console.trace(err);
        await connection.rollback();
        flag = false;
    }
    if (connection) {
        db_cms.releaseConnection(connection);
    }
    return [flag, flag ? '添加成功!' : '添加失败!'];
}

/** 添加音乐列表 到歌单 */
module.exports.add_music_list_to_playlist = add_music_list_to_playlist;
async function add_music_list_to_playlist(playlist_id, music_list_id, owner_id) {

    playlist_id = db_cms.escape(playlist_id);
    owner_id = db_cms.escape(owner_id);
    let result = music_list_id.split(",");
    /** 先去重 */
    result = CommomUtil.distinct(result);
    let music_id_list = [];
    for (let music_id of result) {
        music_id_list.push("'" + music_id + "'")
    }
    /** 查询歌单里是否有该记录 */
    let sql = 'select music_id FROM `music_albums` where albums_id=' + playlist_id + ' and music_id in (' + music_id_list + ')';
    let music_ids = await db_cms.query(sql);
    for (let music_id of music_ids) {

        console.log("---------------------");
        console.log(db_cms.escape(music_id));
        // result.splice(index,1);
    }
    
    console.log("不在表");
    console.log(sql);
    console.log(result);
    music_id_list = [];
    for (let music_id of result) {
        music_id_list.push("'" + music_id + "'")
    }

    /** 查询专辑是否存在 是否属于该用户 */
    sql = 'select albums_id from albums_info where albums_id=' + playlist_id + ' and albums_type=1 and albums_status=0 and owner_id=' + owner_id;
    let albums_flag = await db_cms.queryOne(sql);
    if (albums_flag == null) {
        return [false, '歌单操作错误!'];
    }
    /** 查询音乐是否存在 */
    sql = 'SELECT music_audio_id,music_title,singer,music_status FROM music_info WHERE music_id  in (' + music_id_list + ')';
    let music_infos = await db_cms.query(sql);
    console.log("查询sql");
    console.log(sql);
    console.log(music_infos);
    return [false, '音乐不存在!'];
    if (music_infos.length == 0) {
        return [false, '音乐不存在!'];
    }

    let connection = await db_cms.getConnection();
    if (connection == null) {
        console.trace('trace connection fail');
        return [false, '服务连接异常!'];
    }
    let flag = true;
    try {
        await connection.beginTransaction();

        /** 更新音乐收藏数量 favor_num */
        sql = 'UPDATE `music_info` SET favor_num=favor_num+1 where music_id="' + music_infos[' music_id'] + '"';
        await connection.query(sql);

        /** 更新音乐数量 music_num */
        sql = 'UPDATE albums_info SET music_num=music_num+1 WHERE albums_id=' + playlist_id;
        await connection.query(sql);

        /** 音乐歌单添加关联 */
        sql = 'INSERT INTO music_albums(music_id,albums_id,audio_id,music_title,singer,music_status,create_time) VALUE("' + music_infos['music_id'] + '",' + playlist_id + ',"' + music_infos['music_audio_id'] + '","' + music_infos['music_title'] + '","' + music_infos['singer'] + '","' + music_infos['music_status'] + '",UNIX_TIMESTAMP(NOW()))';
        await connection.query(sql);

        await connection.commit();
    } catch (err) {
        /**
         * TODO 日志系统
         */
        console.trace(err);
        await connection.rollback();
        flag = false;
    }
    if (connection) {
        db_cms.releaseConnection(connection);
    }
    return [flag, flag ? '添加成功!' : '添加失败!'];
}

/** 添加 歌单或专辑到收藏 */
module.exports.add_albums_to_favor = add_albums_to_favor;
async function add_albums_to_favor(albums_id, owner_id) {

    albums_id = db_cms.escape(albums_id);
    owner_id = db_cms.escape(owner_id);

    /** 查询是否已经收藏 */
    let sql = 'SELECT 1 FROM `favor_info` WHERE owner_id=' + owner_id + ' AND object_id=' + albums_id;
    let exist_row = await db_cms.queryOne(sql);
    let exist_flag = true;
    if (exist_row != null && exist_row['1'] == 1) {
        // return [false, '已经收藏过了!'];
        exist_flag = false;
    }
    /** 查询是否存在歌单或专辑 */
    sql = 'SELECT albums_type FROM `albums_info` WHERE albums_id=' + albums_id;
    let albums_info = await db_cms.queryOne(sql);
    if (albums_info == null) {
        return [false, '收藏对象不存在!', false];
    }
    let favor_type = albums_info['albums_type'];
    let favor_id = "fav_" + uuid.v1().replace(/\-/g, '').substring(0, 28);

    let connection = await db_cms.getConnection();
    if (connection == null) {
        console.trace('trace connection fail');
        return [false, '服务连接异常!', false];
    }
    let flag = true;
    try {
        await connection.beginTransaction();

        /** 已收藏状态-需要取消收藏 */
        if (!exist_flag) {
            /** 更新歌单或专辑的收藏数量 follow_num-1 */
            sql = 'UPDATE `albums_info` SET follow_num=follow_num-1 WHERE albums_id=' + albums_id;
            await connection.query(sql);
            /** 删除收藏 */
            sql = 'DELETE FROM `favor_info` WHERE owner_id=' + owner_id + ' and object_id=' + albums_id;
            await connection.query(sql);
        } else {
            /** 更新歌单或专辑的收藏数量 follow_num+1 */
            sql = 'UPDATE `albums_info` SET follow_num=follow_num+1 WHERE albums_id=' + albums_id;
            await connection.query(sql);
            /** 歌单或专辑添加到收藏 */
            sql = 'INSERT INTO `favor_info`(favor_id,owner_id,object_id,favor_type,create_time) VALUE("' + favor_id + '",' + owner_id + ',' + albums_id + ',' + favor_type + ',UNIX_TIMESTAMP(NOW()))';
            await connection.query(sql);
        }

        await connection.commit();
    } catch (err) {
        /**
         * TODO 日志系统
         */
        console.trace(err);
        await connection.rollback();
        flag = false;
    }
    if (connection) {
        db_cms.releaseConnection(connection);
    }
    return [flag, flag ? exist_flag ? '收藏成功!' : '取消收藏!' : '操作出错!', flag ? exist_flag : false];
}


/** 查询我收藏的歌单 */
module.exports.query_my_favor_playlist_or_albums = query_my_favor_playlist_albums;
async function query_my_favor_playlist_albums(begin, plen, owner_id, type) {
    owner_id = db_cms.escape(owner_id);
    /** 我收藏的歌单总数 */
    let sql = 'SELECT count(object_id) total FROM `favor_info` WHERE owner_id=' + owner_id + ' and favor_type=' + type;
    let total = await db_cms.queryOne(sql);
    if (total != null && total['total'] == 0) {
        return [0, []];
    }
    /** 我收藏的歌单 */
    sql = 'SELECT albums_id,cover_id,albums_name,owner_name,music_num,follow_num FROM `albums_info` WHERE albums_id in (select t.object_id from(SELECT object_id FROM `favor_info` WHERE owner_id=' + owner_id + ' and favor_type=' + type + ' order by create_time limit ' + begin + ',' + plen + ')as t )';
    let favor_playlist = await db_cms.query(sql);
    if (favor_playlist instanceof Array && favor_playlist.length > 0) {
        return [total['total'], favor_playlist];
    }
    return [0, []];
}

/** 查询歌单或专辑信息 */
module.exports.query_albums_info = query_albums_info;
async function query_albums_info(albums_id, owner_id) {
    albums_id = db_cms.escape(albums_id);
    owner_id = db_cms.escape(owner_id);
    let sql = 'SELECT cover_id,owner_id,albums_id,albums_name,like_num,comment_num,follow_num,music_num FROM albums_info WHERE albums_id=' + albums_id;
    let albums_info = await db_cms.queryOne(sql);
    if (albums_info == null) {
        return [false, '错误的请求信息！'];
    }
    sql = 'select user_name owner_name,image_id owner_img from ty_user where ty_id="' + albums_info['owner_id'] + '"';
    let user_info = await db_user.queryOne(sql);
    if (user_info == null) {
        return [false, '服务繁忙请稍后！'];
    }

    sql = 'SELECT 1 FROM `favor_info` WHERE owner_id=' + owner_id + ' and object_id=' + albums_id;
    let exist_row = await db_cms.queryOne(sql);
    if (exist_row != null && exist_row['1'] == 1) {
        // return [false, '已经收藏过了!'];
        albums_info['favor_status'] = true;
    } else {
        albums_info['favor_status'] = false;
    }
    Object.assign(albums_info, user_info);
    return [true, albums_info];
}

/** 查询歌单或专辑详情*/
module.exports.query_albums_info2 = query_albums_info2;
async function query_albums_info2(albums_id) {
    albums_id = db_cms.escape(albums_id);
    let sql = 'SELECT cover_id,albums_name,albums_tags,albums_desc,owner_id FROM albums_info WHERE albums_id=' + albums_id + ' and albums_status=0';
    let albums_info = await db_cms.queryOne(sql);
    if (albums_info == null) {
        return [false, '请求出错！'];
    }
    albums_info['albums_id'] = albums_id;
    return [true, albums_info];
}

/** 查询最多播放的歌单列表 */
module.exports.query_play_albums_list = query_play_albums_list;
async function query_play_albums_list(begin, plen) {
    let sql = 'SELECT albums_id,albums_name,play_num,cover_id,owner_id FROM albums_info WHERE albums_type=1 and albums_status=0 ORDER BY play_num DESC LIMIT ' + begin + ',' + plen;
    let music_list = await db_cms.query(sql);
    if (music_list instanceof Array && music_list.length > 0) {
        return music_list;
    }
    return [];
}

/** 根据标签查询歌单列表 */
module.exports.query_cat_play_list = query_cat_play_list;
async function query_cat_play_list(begin, plen, tag) {
    tag = db_cms.escape(tag);
    let sql = 'SELECT albums_id,albums_name,play_num,cover_id,owner_id FROM albums_info WHERE albums_tags LIKE "%' + tag + '%" and albums_type=1 and albums_status=0 ORDER BY play_num DESC LIMIT ' + begin + ',' + plen;
    let music_list = await db_cms.query(sql);
    if (music_list instanceof Array && music_list.length > 0) {
        return music_list;
    }
    return [];
}

module.exports.query_category_albums_list = query_category_albums_list;
async function query_category_albums_list(begin, plen, tag) {
    if (tag == null) {
        return await query_play_albums_list(begin, plen);
    } else {
        return await query_cat_play_list(begin, plen, tag);
    }
}

/** 查询推荐歌单列表 */
module.exports.query_recommend_play_list = query_recommend_play_list;
async function query_recommend_play_list(type, len) {
    let sql = 'SELECT albums_id,albums_name,cover_id FROM `albums_info` WHERE albums_type=' + type + ' and albums_status=0 ORDER BY create_time DESC LIMIT ' + len;
    let music_list = await db_cms.query(sql);
    if (music_list instanceof Array && music_list.length > 0) {
        return music_list;
    }
    return [];
}